/*
 * Copyright (c) 2012 University of Tartu
 */
package org.qsardb.example;

import java.io.*;

import org.qsardb.model.*;
import org.qsardb.storage.directory.*;
import org.qsardb.storage.zipfile.*;

public class CopyExample {

	static
	public void main(String... args) throws Exception {

		if(args.length != 2){
			System.err.println("Usage: java " + CopyExample.class.getName() + " <Input file or directory> <Output file or directory>");

			System.exit(-1);
		}

		File inputFile = new File(args[0]);
		File outputFile = new File(args[1]);

		if(!outputFile.exists()){
			String name = outputFile.getName();

			if(name.indexOf('.') > -1){
				outputFile.createNewFile();
			} else

			{
				outputFile.mkdirs();
			}
		}

		copyQdb(inputFile, outputFile);
	}

	static
	private void copyQdb(File inputFile, File outputFile) throws Exception {
		Storage input = openInput(inputFile);

		try {
			Qdb qdb = new Qdb(input);

			try {
				Storage output = openOutput(outputFile);

				try {
					qdb.copyTo(output);
				} finally {
					output.close();
				}
			} finally {
				qdb.close();
			}
		} finally {
			input.close();
		}
	}

	static
	private Storage openInput(File file) throws IOException {

		if(file.isFile()){
			return new ZipFileInput(file);
		} else

		if(file.isDirectory()){
			return new DirectoryStorage(file);
		}

		throw new IOException(file.getAbsolutePath());
	}

	static
	private Storage openOutput(File file) throws IOException {

		if(file.isFile()){
			return new ZipFileOutput(file);
		} else

		if(file.isDirectory()){
			return new DirectoryStorage(file);
		}

		throw new IOException(file.getAbsolutePath());
	}
}